#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h> 
 
#include "../../../include/common/base.h"
  
#include "../../../include/net/ZNet.h"
 
  

bool SetRecvTimeout( int s, int mtime) 
{  
	struct timeval t;   
	  
	t.tv_sec = mtime / 1000;   
	t.tv_usec= (mtime % 1000) * 1000;   
	
    int optlen = sizeof(timeval) ;  

	 return setsockopt(s,SOL_SOCKET,SO_RCVTIMEO,  (char *) & t, optlen) == 0; 
}

int  rtdb_svr_fun( ZtagAcceptParam * param)
{
	if( param == NULL ) return 0;
	 
	int  sock = param->GetSocket(); 
  
	SetRecvTimeout( sock, 1000 * 20 );
	
	char chrClientIP[64];
	memset(chrClientIP, 0, 64); 
	param->GetClientInfo(chrClientIP); 
 
	base::my_printf("----------rtdb_svr_fun --%s-------------- \n", chrClientIP);
	
	
	while(1)
	{
		try
		{
			int   net_pack_fun = 0; 
			if( ZTcpSocket::RecvInt(sock, &net_pack_fun) <= 0 ) {
				base::my_printf("----------recv  error %s---------------- \n", chrClientIP);
				break;
			}
				
			
			switch(net_pack_fun)
			{
				case REQUEST_REAL_DATA_ALL:
				{
					StdAryRtData  ary; 

					base::my_printf("----------recv recv all rtdata -%s--------------- \n", chrClientIP);
					 
					//get_rtRtdb_all( ary ); 

					int buf_len = 0;

					if( ary.size() >0 )
					{
						/*buf_len = ary.size() * sizeof(RT_DATA_ITEM);

						XCollector   col_buf;  
						col_buf.AppendInt32( buf_len );
						col_buf.Append( ary.data(), buf_len ); 
			 
						ZTcpSocket::Send(sock, (void*)col_buf.GetData(), col_buf.GetSize() );*/
					}
					else {
						buf_len = 0;
						ZTcpSocket::Send(sock, &buf_len, sizeof(int) ); 
					}					
				}
				break;
			}
		
		}
		catch(...)
		{
			base::my_printf("----------catch  error ----%s------------ \n", chrClientIP);
			break;
		}
		
	}
	
	base::my_printf("----------socket thread close ---%s------------- \n", chrClientIP);
	shutdown( sock, 2 );
	close( sock );
	
	return 1;
}